// 收藏/取消收藏云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { itemId, itemType, action } = event // itemType: 'activity' | 'goods', action: 'add' | 'remove'
  
  try {
    // 直接使用openid作为用户标识
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录'
      }
    }
    
    const userOpenid = wxContext.OPENID
    
    // 查找用户收藏记录
    const userCollectionResult = await db.collection('user_collection')
      .where({
        userId: userOpenid
      })
      .get()
    
    let userCollection = null
    let isNewRecord = false
    
    if (userCollectionResult.data.length === 0) {
      // 创建新的收藏记录
      isNewRecord = true
      userCollection = {
        userId: userOpenid,
        activityLikes: [],
        goodsLikes: [],
        createdAt: new Date(),
        updatedAt: new Date()
      }
    } else {
      userCollection = userCollectionResult.data[0]
    }
    
    // 根据类型和操作更新收藏列表
    const likeField = itemType === 'activity' ? 'activityLikes' : 'goodsLikes'
    let likes = userCollection[likeField] || []
    
    if (action === 'add') {
      // 添加收藏，避免重复
      if (!likes.includes(itemId)) {
        likes.push(itemId)
      }
    } else if (action === 'remove') {
      // 取消收藏
      likes = likes.filter(id => id !== itemId)
    }
    
    userCollection[likeField] = likes
    userCollection.updatedAt = new Date()
    
    // 保存到数据库
    if (isNewRecord) {
      await db.collection('user_collection').add({
        data: userCollection
      })
    } else {
      await db.collection('user_collection').doc(userCollection._id).update({
        data: {
          [likeField]: likes,
          updatedAt: new Date()
        }
      })
    }
    
    return {
      success: true,
      message: action === 'add' ? '收藏成功' : '取消收藏成功',
      isCollected: action === 'add'
    }
    
  } catch (error) {
    console.error('收藏操作失败：', error)
    return {
      success: false,
      message: '操作失败，请重试',
      error: error.message
    }
  }
}